#pragma once

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <sys/wait.h>
#include <functional>
#include <pthread.h>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Command.hpp"

static const uint16_t gport = 8888;
static const int blcklog = 8;
static const int gsockfd = -1;

using namespace log_ns;
using server_t = std::function<void(int, InetAddr&)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class TcpServer : public nocopy
{
public:
    TcpServer(server_t server, const uint16_t port = gport)
        : _port(port),
          _listensockfd(gsockfd),
          _isrunning(0),
          _server(server)
    {
    }

    void InitServer()
    {
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "Bind error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "Socket success!\n");
        struct sockaddr_in addr;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_family = AF_INET;

        if (::bind(_listensockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        {
            LOG(FATAL, "Bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "Bind success!\n");

        if (::listen(_listensockfd, blcklog) < 0)
        {
            LOG(FATAL, "listen error!\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success!\n");
    }

    class ThreadData
    {
    public:
        int _sockfd;
        InetAddr _addr;
        TcpServer *_self;

        ThreadData(int sockfd, InetAddr addr, TcpServer *self)
            : _sockfd(sockfd), _addr(addr), _self(self)
        {
        }
    };

    void Loop()
    {
        _isrunning = 1;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            int sockfd = accept(_listensockfd, (struct sockaddr *)&client, &len);
            InetAddr addr(client);

            pthread_t thread;
            ThreadData* td = new ThreadData(sockfd, addr, this);
            pthread_create(&thread, nullptr, Execute, td);
        }
        _isrunning = 0;
    }

    static void *Execute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_self->_server(td->_sockfd, td->_addr);
        ::close(td->_sockfd);
        delete td;
        return nullptr;
    }

    // void Server(int sockfd, InetAddr &addr)
    // {
    //     while (1)
    //     {
    //         char buffer[1024];
    //         int n = read(sockfd, buffer, sizeof(buffer) - 1);
    //         if (n > 0)
    //         {
    //             buffer[n] = 0;
    //             std::string echo_string = "[server echo]";
    //             echo_string += buffer;
    //             write(sockfd, echo_string.c_str(), echo_string.size());
    //             LOG(INFO, "echo success\n");
    //         }
    //         else if (n == 0)
    //         {
    //             LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
    //             break;
    //         }
    //         else
    //         {
    //             LOG(ERROR, "read error\n");
    //             break;
    //         }
    //     }
    // }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
    server_t _server;
};
